var default_config = require('../config/deault.js');
var md5 = require('../utils/md5.js').MD5;
var mongoose = require('./mongoose.js').mongoose;

var UserModel = require('../models/user.js')(mongoose);
module.exports = {
	getNullUser: function() {
		return new UserModel();
	},
	findUserById: function(_id, callback) {
		UserModel.findById(_id, function(err, user) {
			if (err) {
				callback(false, null);
			} else {
				callback(true, user);
			}
		});
	},
	register: function(user, callback) {
		var u = new UserModel({
			name: user.userName,
			gender: user.userGender,
			password: md5(user.userPwd),
			introduction: user.userIntroduction
		});

		u.save(function(err, us) {
			if (err) {
				callback(false, err, null);
			} else {
				callback(true, null, us);
			}
		});
	},
	login: function(user, callback) {
		UserModel.find({
			name: user.userName,
			password: md5(user.userPwd)
		}, function(err, u) {
			if (err) {
				callback(false, err, null);
			} else {
				callback(true, null, u);
			}
		});
	},
	checkUserName: function(userName, callback) {
		UserModel.find({
			name: userName
		}, function(err, us) {
			if (err) {
				callback(false, '数据库异常!');
			} else {
				if (us.length == 0) {
					callback(true, '用户名可用!');
				} else {
					callback(false, '用户名不可用');
				}
			}
		});
	},

	updateUserInfo: function(user, callback) {
		UserModel.findById(user._id, function(err, u) {
			if (err) {
				callback(false, null);
			} else {
				u.gender = user.gender;
				u.introduction = user.introduction;
				u.birthday = user.birthday;
				u.habits = user.habits;
				u.icon = user.icon;
				u.save(function(err, us) {
					if (err) {
						callback(false, u);
					} else {
						callback(true, us);
					}
				});
			}
		});
	}
};